<template>
  <div class="main-box">
    <TreeFilter
      label="name"
      title="资料目录"
      :data="treeFilterData"
      :default-value="initParam.typeId"
      :load="loadNode"
      :lazy="true"
      @change="changeTreeFilter"
    />
    <div class="table-box">
      <ProTable
        ref="proTable"
        title="文件列表"
        row-key="id"
        :indent="20"
        :columns="columns"
        :request-api="getTableList"
        :request-auto="false"
        :init-param="initParam"
        :data-callback="dataCallback"
        :search-col="{ xs: 1, sm: 1, md: 2, lg: 3, xl: 3 }"
      >
        <!-- 表格 header 按钮 -->
        <template #tableHeader>
          <el-button v-auth="'add'" type="primary" @click="openDrawer('新增')"> 上传文件 </el-button>
        </template>
        <template #size="{ row }">
          <span>{{ row.size ?? 0 ? convertFileSizeUnit(row.size) : "--" }}</span>
        </template>
        <!-- 表格操作 -->
        <template #operation="scope">
          <!-- <el-button type="primary" link :icon="View" @click="readhandle(scope.row)"> 查看 </el-button> -->
          <!-- <el-button type="primary" link :icon="EditPen" @click="openDrawer('编辑', scope.row)"> 编辑 </el-button> -->
          <el-button v-auth="'down'" type="primary" link @click="copyToClipboard(scope.row.path, scope.row.originalFileName)">
            复制链接
          </el-button>
          <TriggerContext
            class="trigger-context-status"
            type="dialog"
            :options="{
              title: '文件预览',
              width: '80vw',
              isShowFooter: false,
              slots: {
                default: () => h(Preview, { data: { ...scope.row } })
              }
            }"
          >
            <el-button type="text">预览 </el-button>
          </TriggerContext>
          <el-button v-auth="'down'" type="primary" link @click="downFile(scope.row)"> 下载 </el-button>
          <el-button v-auth="'delete'" type="primary" link @click="deleteAccount(scope.row)"> 删除 </el-button>
        </template>
      </ProTable>
      <fileDrawer ref="drawerRef" />
      <!-- <ImportExcel ref="dialogRef" /> -->
    </div>
  </div>
</template>

<script setup lang="ts" name="treeProTable">
import { onMounted, reactive, ref, getCurrentInstance, h } from "vue";
import { File, Dict } from "@/api/interface";
import { useHandleData } from "@/hooks/useHandleData";
import ProTable from "@/components/ProTable/index.vue";
import TreeFilter from "@/components/TreeFilter/index.vue";
import TriggerContext from "@/components/TriggerContext/index.vue";
import Preview from "@/views/order/order/components/Preview.vue";
const cxt = getCurrentInstance();
const dict = cxt?.appContext.config.globalProperties.$dict;
import fileDrawer from "./fileDrawer.vue";
import { downFilesOpen, copyToClipboard, convertFileSizeUnit } from "@/utils/index";
import { ColumnProps, ProTableInstance } from "@/components/ProTable/interface";
import { deleteMarketDatabase, updateDatabase, downloadDatabasesMarket } from "@/api/modules/sys"; // getUserDepartment getUserList
import { getDict, pageMarketDatabase, insertMarketUpload } from "@/api/modules/sys";

onMounted(() => {
  getTreeFilter({ parentId: dict.marketResources });
});

// 获取 ProTable 元素，调用其获取刷新数据方法（还能获取到当前查询参数，方便导出携带参数）
const proTable = ref<ProTableInstance>();

// 如果表格需要初始化请求参数，直接定义传给 ProTable(之后每次请求都会自动带上该参数，此参数更改之后也会一直带上，改变此参数会自动刷新表格数据)
const initParam = reactive({ typeId: "" });

// 获取 treeFilter 数据
// 当 proTable 的 requestAuto 属性为 false，不会自动请求表格数据，等待 treeFilter 数据回来之后，更改 initParam.departmentId 的值，才会触发请求 proTable 数据
const treeFilterData = ref<any>([]);

const getTreeFilter = async (params: Dict.ResDictList) => {
  let { data } = await getDict(params);
  data =
    (data &&
      data.map(item => {
        item.hasChild = !item.hasChild;
        return item;
      })) ||
    [];
  treeFilterData.value = data;
  initParam.typeId = treeFilterData.value[0].id;
};

// 树形筛选切换
const changeTreeFilter = (val: string) => {
  proTable.value!.pageable.pageNum = 1;
  initParam.typeId = val;
  console.log(val);
};

// 表格配置项
const columns: ColumnProps<File.ResFileList>[] = [
  { type: "index", label: "#", width: 80 },
  { prop: "originalFileName", label: "文件原名称" },
  { prop: "name", label: "文件名", isShow: false },
  { prop: "path", label: "路径", isShow: false },
  { prop: "downNumber", label: "下载次数" },
  {
    prop: "size",
    label: "大小"
  },
  {
    prop: "remark",
    label: "备注"
  },
  { prop: "operation", label: "操作", width: 300, fixed: "right" }
];
// td
const getTableList = (params: any) => {
  const newParams = {
    currentPage: params.pageNum,
    searchKey: params.searchKey ? params.searchKey : "",
    typeId: params.typeId ? params.typeId : ""
  };
  return pageMarketDatabase(newParams);
};
const dataCallback = (data: any) => {
  // 处理返回参数
  return {
    list: data.records,
    total: data.total,
    pageNum: data.current,
    pageSize: data.size
  };
};
// 删除用户信息
const deleteAccount = async (params: File.ResFileList) => {
  await useHandleData(deleteMarketDatabase, { id: params.id }, `删除【${params.originalFileName}】资料`);
  proTable.value?.getTableList();
};
// 下载文件
const downFile = async (params: File.ResFileList) => {
  await downloadDatabasesMarket({ name: params.name });
  proTable.value?.getTableList();
  if (params.customPath) {
    window.open(params.customPath);
  } else {
    downFilesOpen(params.path, params.originalFileName);
  }
};
// 打开 drawer(新增、查看、编辑)
const drawerRef = ref<InstanceType<typeof fileDrawer> | null>(null);
const openDrawer = (title: string, row: Partial<File.ResFileList> = {}) => {
  const params = {
    title,
    row: { ...row },
    isView: title === "查看",
    api: title === "新增" ? insertMarketUpload : title === "编辑" ? updateDatabase : undefined,
    getTableList: proTable.value?.getTableList,
    getDict,
    typeId: initParam.typeId
  };
  console.log(initParam.typeId);
  drawerRef.value?.acceptParams(params);
};

// 加载字典数据
const loadNode = async (node: Node, resolve: (data: Dict.ResDictList[]) => void) => {
  if (node.key) {
    let { data } = await getDict({ parentId: node.key });
    data =
      (data &&
        data.map(item => {
          item.hasChild = !item.hasChild;
          return item;
        })) ||
      [];
    resolve(data);
  }
};
</script>
<style scoped lang="scss">
.trigger-context {
  display: inline;
  margin: 0 12px;
}
</style>
